import { modal } from 'vue-strap'
import DatePicker from 'vue-datepicker'
import extend from 'extend'
import getDatePickerOption from '../../../util/date-picker-option'
import { newIndexAd, showMsg } from '../../../vuex/action'

const defaultAd = {
  title: '',
  startTime: '',
  endTime: '',
  file: '',
  type: -1, // int
  location: '',
  buttonDesc: '',
  showToNewUser: 0,
  forceExternalBrowser: 0, // int
  channel: ''
}

const validation = {
  ad(data) {
    for (let name in data) {
      if (name === 'type' && data[name] < 0) {
        return false
      }
      if (name !== 'channel' && (data[name] + '').length === 0) {
        return false
      }
    }
    return true
  },
  time(start, end) {
    return start < end
  }
}

export default {
  name: 'IndexNewAd',
  components: {
    'vue-modal': modal,
    'vue-date-picker': DatePicker
  },
  data() {
    return {
      showNewAdModal: false,
      ad: extend(true, {}, defaultAd),
      datePickerOption: getDatePickerOption()
    }
  },
  vuex: {
    actions: {
      xNewIndexAd: newIndexAd,
      xShowMsg: showMsg
    }
  },
  methods: {
    trim(val) {
      if (typeof val === 'string') {
        return val.replace(/(^ +)|( +$)/g, '')
      } else {
        return val
      }
    },
    resetAd() {
      this.ad = extend(true, {}, defaultAd)
    },
    newAd() {
      this.showNewAdModal = true
    },
    submit() {
      var formData = new FormData()
      var ad = extend(true, {}, this.ad)
      var valid = validation.ad(ad)
      if (!valid) {
        return this.xShowMsg({
          type: 'danger',
          content: '* 标记的均为必填/必选项'
        })
      }
      var timeValid = validation.time(ad.startTime, ad.endTime)
      if (!timeValid) {
        return this.xShowMsg({
          type: 'danger',
          content: '开始时间应早于结束时间'
        })
      }

      ad.type = +ad.type
      ad.forceExternalBrowser = +ad.forceExternalBrowser
      for (let name in ad) {
        if (name !== 'file') {
          formData.append(name, this.trim(ad[name]))
        }
      }
      formData.append('file', this.$els.file.files[0])
      this.xNewIndexAd(formData)
        .then(() => {
          this.resetAd()
          this.showNewAdModal = false
        })
        .catch((res) => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  },
  ready() {}
}
